if (!localStorage.getItem('token') && !location.href.includes('/login'))
  location.href = '/bigevent/home/login.html';
//密码验证
let form = layui.form;
let image = $('.cropper-box #image');
function fileEvent(option) {
  $('#chooseImage').click(() => {
    $('#file').click();
  });
  $('#file').change(function () {
    let upImage = this.files[0];
    let url = URL.createObjectURL(upImage);
    image.cropper('destroy').attr('src', url).cropper(option);
  });
}
function getCategory() {
  return $.ajax({
    url: '/my/article/cates',
    success(res) {
      if (res.status !== 0) {
        layer.msg(res.message);
      }
      if (location.href.includes('/category')) {
        let str = template('articleItem', res);
        $('tbody').html(str);
      } else if (location.href.includes('/article.html')) {
        let str = template('cateSltAtc', res);
        $('#filterForm').prepend($(str));
        form.render('select');
      } else if (
        location.href.includes('/release.html') ||
        location.href.includes('/edit.html')
      ) {
        // let str = template('cateSltAtc', res);
        // $('[name="cate_id"]').prepend($(str));
        // form.render('select');

        let str = template('cateSltAtc', res);
        $('[name="cate_id"]').prepend($(str));
        form.render('select');
      }
    },
  });
}
form.verify({
  pass: [/^[\S]{6,12}$/, '密码必须6到12位，且不能出现空格'],
  repass(value) {
    if (value !== $('.password').val()) {
      return '两次输入的密码需要保持一致';
    }
  },
  newpwd(value) {
    if (value === $('.oldPwd').val()) {
      return '新密码不能与旧密码一致,请重新输入';
    }
  },
  email(val) {
    let res = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(val);
    if (!res) {
      return '邮箱格式不正确,请重新输入';
    }
  },
  nickname(val) {
    if (val.length > 4 || val.length < 2 || !/[\u4e00-\u9fa5]/gm.test(val))
      return '请输入2-4个中文字符';
  },
});
$(() => {
  $.ajaxPrefilter((options) => {
    options.url = 'http://ajax.frontend.itheima.net' + options.url;

    if (options.url.includes('/my')) {
      options.headers = {
        Authorization: localStorage.getItem('token'),
      };
      // if (options.url.includes('/updatepwd')) return;
      options.complete = function (xhr) {
        if (
          xhr.responseJSON.status == 1 &&
          xhr.responseJSON.message.includes('身份认证失败')
        ) {
          layer.msg(xhr.responseJSON.message, function () {
            location.href = '/bigevent/home/login.html';
            localStorage.removeItem('token');
          });
        }
      };
    }
  });
});
